"""
系统优化方案：轻量级操作处理器
解决简单操作触发不必要API调用的问题

作者: 性能优化专家
日期: 2025-01-05
"""

import re
import logging
from typing import Dict, Any, Optional, List
from enum import Enum
from dataclasses import dataclass

logger = logging.getLogger(__name__)

class OperationType(Enum):
    """操作类型枚举"""
    SIMPLE_CRUD = "simple_crud"      # 简单的增删改查
    COMPLEX_QUERY = "complex_query"   # 复杂查询分析
    CONVERSATIONAL = "conversational" # 对话交互
    UNKNOWN = "unknown"              # 未知类型

class AgentType(Enum):
    """智能体类型枚举"""
    DINGTALK = "dingtalk_agent"
    TEXT2SQL = "text2sql_agent"
    SUPERVISOR = "supervisor"
    GENERAL = "general"

@dataclass
class OperationClassification:
    """操作分类结果"""
    operation_type: OperationType
    agent_type: AgentType
    confidence: float
    requires_memory: bool
    requires_embedding: bool
    estimated_cost: float

class LightweightOperationClassifier:
    """轻量级操作分类器"""
    
    def __init__(self):
        # 简单操作模式定义
        self.simple_patterns = {
            AgentType.DINGTALK: {
                "todo": [
                    r"(创建|添加|加入).*(待办|任务|todo)",
                    r"(查看|显示|列出).*(待办|任务|todo)",
                    r"(完成|删除|取消).*(待办|任务|todo)",
                    r".*待办.*",
                    r".*下班.*加入.*"
                ],
                "calendar": [
                    r"(查看|显示).*(日程|安排|会议)",
                    r"(创建|安排|预定).*(会议|日程)",
                    r".*日程.*",
                    r".*会议.*"
                ],
                "contact": [
                    r"(搜索|查找|联系).*(同事|联系人)",
                    r".*通讯录.*",
                    r".*联系人.*",
                    r"搜索.*的联系方式",
                    r"查找.*联系.*",
                    r".*联系方式.*"
                ]
            },
            AgentType.TEXT2SQL: {
                "query": [
                    r"(查询|搜索|统计).*(电影|客户|数据)",
                    r".*票房.*",
                    r".*演员.*",
                    r".*电影.*",
                    r"(多少|几个|统计).*"
                ]
            }
        }
        
        # 复杂操作模式
        self.complex_patterns = [
            r".*分析.*",
            r".*比较.*",
            r".*推荐.*基于.*",
            r".*解释.*为什么.*",
            r".*总结.*报告.*",
            r".*趋势.*",
            r".*统计.*",
            r".*收入.*情况.*",
            r".*数据.*分析.*"
        ]
        
        # 对话模式
        self.conversational_patterns = [
            r"^(你好|hello|hi|您好)",
            r".*功能.*介绍.*",
            r".*帮助.*",
            r".*能做什么.*",
            r".*能干什么.*",
            r".*有什么功能.*",
            r".*可以做什么.*",
            r".*会什么.*"
        ]
    
    def classify_operation(self, user_input: str) -> OperationClassification:
        """
        分类用户操作
        
        Args:
            user_input: 用户输入
            
        Returns:
            操作分类结果
        """
        user_input_lower = user_input.lower().strip()
        
        # 1. 检查对话类型
        if self._match_patterns(user_input_lower, self.conversational_patterns):
            return OperationClassification(
                operation_type=OperationType.CONVERSATIONAL,
                agent_type=AgentType.SUPERVISOR,
                confidence=0.9,
                requires_memory=False,
                requires_embedding=False,
                estimated_cost=0.0002  # 只需要一次Chat API调用
            )

        # 2. 🎯 优先检查复杂操作（避免被简单操作误分类）
        if self._match_patterns(user_input_lower, self.complex_patterns):
            # 判断是否是Text2SQL相关的复杂查询
            text2sql_keywords = ["电影", "票房", "演员", "客户", "数据", "统计", "分析", "查询"]
            if any(keyword in user_input_lower for keyword in text2sql_keywords):
                agent_type = AgentType.TEXT2SQL
            else:
                agent_type = AgentType.GENERAL

            return OperationClassification(
                operation_type=OperationType.COMPLEX_QUERY,
                agent_type=agent_type,
                confidence=0.8,
                requires_memory=True,
                requires_embedding=True,
                estimated_cost=0.002  # 需要多次API调用
            )

        # 3. 检查简单操作
        for agent_type, categories in self.simple_patterns.items():
            for category, patterns in categories.items():
                if self._match_patterns(user_input_lower, patterns):
                    return OperationClassification(
                        operation_type=OperationType.SIMPLE_CRUD,
                        agent_type=agent_type,
                        confidence=0.85,
                        requires_memory=False,  # 简单操作不需要记忆
                        requires_embedding=False,  # 简单操作不需要嵌入
                        estimated_cost=0.0002  # 只需要一次Chat API调用
                    )
        
        # 4. 默认分类（需要LLM判断）
        return OperationClassification(
            operation_type=OperationType.UNKNOWN,
            agent_type=AgentType.GENERAL,
            confidence=0.5,
            requires_memory=True,
            requires_embedding=True,
            estimated_cost=0.003  # 需要LLM路由 + 其他API调用
        )
    
    def _match_patterns(self, text: str, patterns: List[str]) -> bool:
        """匹配模式列表"""
        return any(re.search(pattern, text) for pattern in patterns)

class OptimizedSupervisor:
    """优化后的Supervisor"""
    
    def __init__(self):
        self.classifier = LightweightOperationClassifier()
        self.stats = {
            "total_requests": 0,
            "simple_operations": 0,
            "complex_operations": 0,
            "api_calls_saved": 0,
            "cost_saved": 0.0
        }
    
    def route_request(self, user_input: str) -> Dict[str, Any]:
        """
        优化的请求路由
        
        Args:
            user_input: 用户输入
            
        Returns:
            路由决策结果
        """
        self.stats["total_requests"] += 1
        
        # 分类操作
        classification = self.classifier.classify_operation(user_input)
        
        # 更新统计
        if classification.operation_type == OperationType.SIMPLE_CRUD:
            self.stats["simple_operations"] += 1
            self.stats["api_calls_saved"] += 4  # 节省4次嵌入API调用
            self.stats["cost_saved"] += 0.0018  # 节省成本
        elif classification.operation_type == OperationType.COMPLEX_QUERY:
            self.stats["complex_operations"] += 1
        
        # 记录决策
        logger.info(f"🎯 轻量级路由: '{user_input[:30]}...' -> {classification.agent_type.value}")
        logger.info(f"   操作类型: {classification.operation_type.value}")
        logger.info(f"   需要记忆: {classification.requires_memory}")
        logger.info(f"   需要嵌入: {classification.requires_embedding}")
        logger.info(f"   预估成本: ${classification.estimated_cost:.4f}")
        
        return {
            "agent_type": classification.agent_type.value,
            "operation_type": classification.operation_type.value,
            "requires_memory": classification.requires_memory,
            "requires_embedding": classification.requires_embedding,
            "confidence": classification.confidence,
            "estimated_cost": classification.estimated_cost,
            "optimization_applied": classification.operation_type == OperationType.SIMPLE_CRUD
        }
    
    def get_optimization_stats(self) -> Dict[str, Any]:
        """获取优化统计"""
        total = self.stats["total_requests"]
        if total == 0:
            return self.stats
        
        return {
            **self.stats,
            "simple_operation_rate": (self.stats["simple_operations"] / total) * 100,
            "optimization_rate": (self.stats["simple_operations"] / total) * 100,
            "avg_cost_per_request": self.stats["cost_saved"] / total if total > 0 else 0
        }

class ConditionalMemoryManager:
    """条件性记忆管理器"""
    
    def __init__(self):
        self.storage_stats = {
            "total_conversations": 0,
            "stored_conversations": 0,
            "skipped_conversations": 0,
            "embedding_calls_saved": 0
        }
    
    def should_store_conversation(
        self, 
        user_input: str, 
        ai_response: str, 
        operation_type: OperationType,
        agent_type: AgentType
    ) -> bool:
        """
        判断是否应该存储对话到记忆系统
        
        Args:
            user_input: 用户输入
            ai_response: AI回复
            operation_type: 操作类型
            agent_type: 智能体类型
            
        Returns:
            是否需要存储
        """
        self.storage_stats["total_conversations"] += 1
        
        # 简单CRUD操作不存储
        if operation_type == OperationType.SIMPLE_CRUD:
            self.storage_stats["skipped_conversations"] += 1
            self.storage_stats["embedding_calls_saved"] += 2  # 节省用户消息和AI回复的嵌入
            logger.info(f"⚡ 跳过记忆存储: 简单操作 ({operation_type.value})")
            return False
        
        # 对话类型的问候不存储
        if operation_type == OperationType.CONVERSATIONAL and len(user_input) < 20:
            self.storage_stats["skipped_conversations"] += 1
            self.storage_stats["embedding_calls_saved"] += 2
            logger.info(f"⚡ 跳过记忆存储: 简单对话")
            return False
        
        # 错误回复不存储
        if "抱歉" in ai_response or "错误" in ai_response or len(ai_response) < 10:
            self.storage_stats["skipped_conversations"] += 1
            self.storage_stats["embedding_calls_saved"] += 2
            logger.info(f"⚡ 跳过记忆存储: 错误回复")
            return False

        # 复杂查询需要存储（特殊处理）
        if operation_type == OperationType.COMPLEX_QUERY:
            self.storage_stats["stored_conversations"] += 1
            logger.info(f"💾 存储到记忆: 复杂查询 ({operation_type.value})")
            return True
        
        # 复杂查询需要存储
        self.storage_stats["stored_conversations"] += 1
        logger.info(f"💾 存储到记忆: 复杂操作 ({operation_type.value})")
        return True
    
    def get_memory_stats(self) -> Dict[str, Any]:
        """获取记忆统计"""
        total = self.storage_stats["total_conversations"]
        if total == 0:
            return self.storage_stats
        
        return {
            **self.storage_stats,
            "storage_rate": (self.storage_stats["stored_conversations"] / total) * 100,
            "skip_rate": (self.storage_stats["skipped_conversations"] / total) * 100,
            "embedding_savings": self.storage_stats["embedding_calls_saved"]
        }

# 全局实例
_optimized_supervisor = None
_conditional_memory = None

def get_optimized_supervisor() -> OptimizedSupervisor:
    """获取优化后的Supervisor实例"""
    global _optimized_supervisor
    if _optimized_supervisor is None:
        _optimized_supervisor = OptimizedSupervisor()
    return _optimized_supervisor

def get_conditional_memory_manager() -> ConditionalMemoryManager:
    """获取条件性记忆管理器实例"""
    global _conditional_memory
    if _conditional_memory is None:
        _conditional_memory = ConditionalMemoryManager()
    return _conditional_memory

def log_optimization_summary():
    """记录优化效果总结"""
    supervisor = get_optimized_supervisor()
    memory_manager = get_conditional_memory_manager()
    
    supervisor_stats = supervisor.get_optimization_stats()
    memory_stats = memory_manager.get_memory_stats()
    
    logger.info("📊 系统优化效果总结:")
    logger.info(f"   总请求数: {supervisor_stats['total_requests']}")
    logger.info(f"   简单操作: {supervisor_stats['simple_operations']} ({supervisor_stats.get('simple_operation_rate', 0):.1f}%)")
    logger.info(f"   API调用节省: {supervisor_stats['api_calls_saved']}次")
    logger.info(f"   成本节省: ${supervisor_stats['cost_saved']:.4f}")
    logger.info(f"   记忆存储跳过: {memory_stats['skipped_conversations']}次")
    logger.info(f"   嵌入调用节省: {memory_stats['embedding_calls_saved']}次")
